//
//  AddPlanViewController.m
//  wangzhe
//
//  Created by 李 佳伟 on 2017/11/17.
//  Copyright © 2017年 李 佳伟. All rights reserved.
//

#import "AddPlanViewController.h"
#import "JTCSM.h"
#import "MyInfoView.h"
#import "ZYRadioButton.h"
//#import "PGDatePicker.h"
#import "NSDate+PGCategory.h"
#import "BRStringPickerView.h"
#import "GetInfoClass.h"
#import "MyBankCardModel.h"
#import "PlanView.h"
#import "HuanKuanAlertview.h"
#import "KYAlertView.h"


@interface AddPlanViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,HuanKuanAlertviewDelegate>
{
    MyInfoView *timestartView;
//    MyInfoView *timeView;
    MyInfoView *typeView;
    MyInfoView *moneyView;
    MyInfoView *statusView;
    
    UITextField *baozhengTextfield;
    UIView *lineView;
    UIButton *LoginBtn;
    
    NSString *type;
    NSString *status;
    NSString *startdata;
    NSString *enddata;
    NSString *margin;
    NSString *total_price;
    NSString *baozhengjin;
    
    float feilv;
    
    MyBankCardModel *infomodel;
    
    
    UITableView *_tableview;
    NSMutableArray *titlearray;
    NSString *client_num;
    
    NSString *idd;
    NSString *card_id ;
    NSString *truename ;
    NSString *bank_card ;
    NSString *bank_tel;
    NSString *subType;
    NSString *subcode;
    UITextField *subtextfield;
    
    UILabel *baozhengjinlabel;
    
}
@end

@implementation AddPlanViewController

- (void)gotBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    [df isRemoveTarbar:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    leftBarButtonItems_rightBarButtonItems *leftbtn = KCUSTOMNAVIGSTION_ALLOC;
    self.navigationItem.leftBarButtonItem = [leftbtn setBarButtonItemsImageName:@"fanhui.png" frame:KLeftBarButtonItemFrame_image target:self SEL:@selector(gotBack)];
    client_num = @"";
    status = @"";
    margin = @"";

    self.navigationItem.rightBarButtonItem = [leftbtn setBarButtonItemsTitle:@"提交" frame:CGRectMake(0, 0, 40, 44) target:self SEL:@selector(tijiao)];
    [self therequest];
    // Do any additional setup after loading the view.
    [self layouttabelview];
    
}

- (UIView *)layoutView{
    CGFloat viewHeight = 50;
    CGFloat space = 20;
    
    UIView *headerView = [[UIView alloc]init];
    headerView.userInteractionEnabled = YES;
    timestartView= [[MyInfoView alloc]initWithFrame:CGRectMake(space, 0, KCONTROLLERWith-2*space, viewHeight) imagename:nil title:@"开始日期" placeholder:nil isShowLabel:ImageandlabelViewType radioBtnIndex:0 GroupId:nil];
    [headerView addSubview:timestartView];
    [df addTapGestureRecognizerWithTarget:self action:@selector(showDataPick) andaddView:timestartView];
    
//    timeView = [[MyInfoView alloc]initWithFrame:CGRectMake(space, KVIEW_Y(timestartView), KCONTROLLERWith-2*space, viewHeight) imagename:nil title:@"结束日期" isShowLabel:ImageandlabelViewType radioBtnIndex:0 GroupId:nil];
//    [headerView addSubview:timeView];
//    [df addTapGestureRecognizerWithTarget:self action:@selector(showendDataPick) andaddView:timeView];
    
    typeView = [[MyInfoView alloc]initWithFrame:CGRectMake(space, KVIEW_Y(timestartView), KCONTROLLERWith-2*space, viewHeight) imagename:nil title:@"还款类别"placeholder:nil isShowLabel:ImageandlabelViewType radioBtnIndex:0 GroupId:nil];
    [headerView addSubview:typeView];
    [df addTapGestureRecognizerWithTarget:self action:@selector(xuanzeRiqi:) andaddView:typeView];
    
    moneyView = [[MyInfoView alloc]initWithFrame:CGRectMake(space, KVIEW_Y(typeView), KCONTROLLERWith-2*space, viewHeight) imagename:nil title:@"还款总金额"placeholder:@"输入金额" isShowLabel:textfieldtype radioBtnIndex:0 GroupId:nil];
    [headerView addSubview:moneyView];
    moneyView.textfield.delegate = self;
    [moneyView.textfield addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];

    
    statusView = [[MyInfoView alloc]initWithFrame:CGRectMake(space, KVIEW_Y(moneyView), KCONTROLLERWith-2*space, viewHeight) imagename:nil title:@"保障金" placeholder:@"输入保障金金额" isShowLabel:textfieldtype radioBtnIndex:0 GroupId:nil];
    [headerView addSubview:statusView];
    statusView.textfield.delegate = self;
    [statusView.textfield addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
    
    baozhengjinlabel = [UILabel initWithFrame:CGRectMake(space, KVIEW_Y(statusView)+10, KCONTROLLERWith-2*space, 40) text:@"" font:12 textAlignment:NSTextAlignmentRight texcolor:RGBACOLOR(193, 193, 193, 1) backgroundColor:nil];
    [headerView addSubview:baozhengjinlabel];
    
//    baozhengTextfield = [UITextField initWithframe:CGRectMake(space, KVIEW_Y(statusView), KCONTROLLERWith-2*space, viewHeight) backgrandColor:nil placeholder:@"填写保证金金额" textAlignment:NSTextAlignmentLeft font:16 texcolor:RGBACOLOR(89, 89, 89, 1)];
//    baozhengTextfield.hidden = YES;
//    [headerView addSubview:baozhengTextfield];
//    [baozhengTextfield addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
    
    lineView = [[UIView alloc]initWithFrame:CGRectMake(space, KVIEW_Y(statusView), KCONTROLLERWith-2*space, 1)];
    lineView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    lineView.hidden = YES;
    [headerView addSubview:lineView];
    
//    CGFloat radioSize = 22;
//    CGFloat changeSpace = 10;
//    CGFloat viewWidth = statusView.frame.size.width;
//
//    NSString *statusOne = @"手动";
//    CGRect rect1 = [df labelHeightWithContent:statusOne height:viewHeight font:14];
//    UILabel *labelOne = [UILabel initWithFrame:CGRectMake(viewWidth-rect1.size.width, 0, rect1.size.width, viewHeight) text:statusOne font:14 textAlignment:NSTextAlignmentLeft texcolor:RGBACOLOR(89, 89, 89, 1) backgroundColor:nil];
//    [statusView addSubview:labelOne];
//
//
//    ZYRadioButton *oneradioBtn = [[ZYRadioButton alloc]initWithGroupId:@"huankuantype" index:0];
//    oneradioBtn.frame = CGRectMake(labelOne.frame.origin.x-changeSpace-radioSize, (viewHeight-radioSize)/2, radioSize, radioSize);
//    [statusView addSubview:oneradioBtn];
//
//    NSString *statustwo = @"默认";
//    UILabel *labeltwo = [UILabel initWithFrame:CGRectMake(oneradioBtn.frame.origin.x-changeSpace*3-rect1.size.width, 0, rect1.size.width, viewHeight) text:statustwo font:14 textAlignment:NSTextAlignmentLeft texcolor:RGBACOLOR(89, 89, 89, 1) backgroundColor:nil];
//    [statusView addSubview:labeltwo];
//
//
//    ZYRadioButton *tworadioBtn = [[ZYRadioButton alloc]initWithGroupId:@"huankuantype" index:1];
//    tworadioBtn.frame = CGRectMake(labeltwo.frame.origin.x-changeSpace-radioSize, (viewHeight-radioSize)/2, radioSize, radioSize);
//    [statusView addSubview:tworadioBtn];
//    [ZYRadioButton addObserverForGroupId:@"huankuantype" observer:self];
//
    
    CGFloat btnspace = 20;
    CGFloat btnHeight = 50;
    LoginBtn =[[UIButton alloc] initWithFrame:CGRectMake(btnspace, KVIEW_Y(baozhengjinlabel)+20 , (KCONTROLLERWith-2*btnspace), btnHeight)];
    LoginBtn.backgroundColor =RGBACOLOR(227, 68, 40, 1);
    [LoginBtn setTitle:@"增加计划到列表" forState:UIControlStateNormal];
    [LoginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //[df layerWithView:LoginBtn radius:4 width:2 color:RGBACOLOR(172,134,171, 1)];
    [LoginBtn addTarget:self action:@selector(gotoMainV) forControlEvents:UIControlEventTouchUpInside];
    LoginBtn.tag = 10002;
    [headerView addSubview:LoginBtn];
    [df layerWithView:LoginBtn radius:btnHeight/2 width:0 color:nil];
    
    headerView.frame = CGRectMake(0, 0, KCONTROLLERWith, KVIEW_Y(LoginBtn));
    
    return headerView;
    
}
#pragma mark 监听textfield 的变化
- (void)valueChanged:(UITextField *)textfield{
    
    
    if (textfield == statusView.textfield) {
        
        
        margin = textfield.text;
        
    } else if(textfield==subtextfield){
        subcode = textfield.text;
        
    }else{
        
        
        total_price = textfield.text;
        [self getbaozhengjin];
        
        
    }
    
}
- (void)gotoMainV{
    
    [self.view endEditing:YES];
    [titlearray removeAllObjects];
    titlearray = nil;
    titlearray = [NSMutableArray array];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    LoadData *request = [[LoadData alloc]init];
    [dict setObject:KTokenString==nil?@"":KTokenString forKey:@"token"];
    [dict setObject:self.card_id forKey:@"card_id"];
    [dict setObject:startdata==nil?@"":startdata forKey:@"time_start"];
//    [dict setObject:enddata==nil?@"":enddata forKey:@"time_end"];
    [dict setObject:type==nil?@"":type forKey:@"type_id"];
    [dict setObject:total_price==nil?@"":total_price forKey:@"total_price"];
//    [dict setObject:status==nil?@"":status forKey:@"method"];
    [dict setObject:margin==nil?@"":margin forKey:@"margin"];
    NSLog(@"%@",dict);
    
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"CreditPlan/create") withDict:dict superView:self.view isAddtag:NO  Block:^(id result) {
        
//        SONObject(response).getString("card_id");
//        String mtruename = new JSONObject(response).getString("truename");
//        String mbank_card = new JSONObject(response).getString("bank_card");
//        String mbank_tel = new JSONObject(response).getString("bank_tel");
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        
        NSDictionary *subdict = KResultOfKey(@"data");
        NSString *issubreturn;
        if ([subdict isKindOfClass:[NSDictionary class]] && subdict != nil) {
            issubreturn = [NSString stringWithFormat:@"%@",[subdict objectForKey:@"sub-status"]];
        }
        
        if ([issubreturn isEqualToString:@"11"]) {
            idd = [subdict objectForKey:@"id"];
            card_id = [subdict objectForKey:@"card_id"];
            truename = [subdict objectForKey:@"truename"];
            bank_card = [subdict objectForKey:@"bank_card"];
            bank_tel = [subdict objectForKey:@"bank_tel"];
            subType = [subdict objectForKey:@"type"];
            
            
            NSString *name = [truename stringByReplacingCharactersInRange:NSMakeRange(1, truename.length-1) withString:@"*"];
            NSString *bankcard = [bank_card stringByReplacingCharactersInRange:NSMakeRange(0, bank_card.length-3) withString:@"****"];
            NSString *banktel = [bank_tel stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            
            NSString *message = [NSString stringWithFormat:@"持卡人：%@\n\n卡号：%@\n\n手机号：%@",name,bankcard,banktel];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本次操作需要短信确认" message:message delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"下一步",nil];
            alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
            [[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
            [[alert textFieldAtIndex:0] setPlaceholder:@"请输入验证码"];
            subtextfield = (UITextField*)[alert textFieldAtIndex:0];
            [subtextfield addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
            subtextfield.delegate = self;
            alert.alertViewClickedButtonAtIndexBlock = ^(UIAlertView *alert ,NSUInteger index) {
                
                if (index == 0) {
                    
                    NSLog(@"取消");
                    
                }else  if (index == 1) {
                    
                    NSLog(@"好");
                    [self yanzhengmaReques];
                    
                }
                
            };
            
            [alert show];

            
            
            
        }else if ([isreturn isEqualToString:@"1"]) {
            
            NSDictionary *dict = KResultOfKey(@"data");
            NSArray *array = [dict objectForKey:@"plan"];
            for (NSDictionary *mydict in array) {
               MyBankCardModel *model = [MyBankCardModel whc_ModelWithJson:mydict];
                model.client_num = [dict objectForKey:@"client_num"];
                [titlearray addObject:model];
                
            }
            [_tableview reloadData];

        }else{
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
            //            [self theRequestOftuwenyanzhengma];
        }
        
    }];

}
- (void)yanzhengmaReques{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    LoadData *request = [[LoadData alloc]init];
    [dict setObject:KTokenString==nil?@"":KTokenString forKey:@"token"];
    [dict setObject:idd forKey:@"id"];
    [dict setObject:card_id==nil?@"":card_id forKey:@"card_id"];
    [dict setObject:subType==nil?@"":subType forKey:@"type"];
    [dict setObject:subcode==nil?@"":subcode forKey:@"code"];
    
    NSLog(@"%@",dict);
    
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"CreditCard/platformBind") withDict:dict superView:self.view isAddtag:NO  Block:^(id result) {
        if (![result isKindOfClass:[NSDictionary class]]) {
            return ;
        }
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            [self gotoMainV];
        }else{
            [df showAlertWithTitle:[result objectForKey:@"msg"] message:nil btn1:@"返回" btn2:nil btn3:nil delegate:nil tag:0];
        }
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    for (UITextField *textfield in [moneyView subviews]) {
        [textfield resignFirstResponder];
    }
    
}

- (void)showDataPick{

    NSString *dateTime = [self getNowTimeTimestamp2:nil];
    
    NSInteger huanri = [self.huanri integerValue];
    NSInteger starttime;
    if ([self gethourWithTime:dateTime] <17) {
        starttime = [dateTime integerValue];
    }else{
        starttime = [dateTime integerValue]+86400;
    }
    
    if ([self getdayWithTime:[NSString stringWithFormat:@"%ld",starttime]] == huanri) {
        starttime += 86400;
    }
    NSInteger endtime = starttime;

    
    while (true) {
        endtime+=86400;
        if ([self getdayWithTime:[NSString stringWithFormat:@"%ld",endtime]] == huanri) {
            endtime-=86400;
            break;
        }
        if ([self getdayWithTime:[NSString stringWithFormat:@"%ld",endtime]]== [self.zhangdanri integerValue]) {
            starttime = endtime+86400;
        }
    }
    
    
    
    // 自定义单列字符串
    NSMutableArray *dataarray = [self getDataArrayWithStartData:starttime endStart:endtime];
    enddata = [dataarray lastObject];
    [BRStringPickerView showStringPickerWithTitle:@"选择时间" dataSource:dataarray defaultSelValue:dataarray[0] isAutoSelect:YES resultBlock:^(id selectValue) {
        
        timestartView.footerLabel.text = selectValue;
        startdata = selectValue;
    
        [self getbaozhengjin];
        
    }];
    
}

//- (void)showendDataPick{
//
//    NSString *dateTime = [self getNowTimeTimestamp2:nil];
//    NSInteger huanri = [self.huanri integerValue];
//    NSInteger starttime;
//    if ([self gethourWithTime:dateTime] <17) {
//        starttime = [dateTime integerValue];
//    }else{
//        starttime = [dateTime integerValue]+86400;
//    }
//
//    if ([self getdayWithTime:[NSString stringWithFormat:@"%ld",starttime]] == huanri) {
//        starttime += 86400;
//    }
//    NSInteger endtime = starttime;
//    while (true) {
//        endtime+=86400;
//
//        if ([self getdayWithTime:[NSString stringWithFormat:@"%ld",endtime]]== [self.zhangdanri integerValue]) {
//            starttime = endtime+86400;
//        }
//        if ([self getdayWithTime:[NSString stringWithFormat:@"%ld",endtime]] == huanri) {
//            endtime-=86400;
//            break;
//        }
//
//    }
//
//    // 自定义单列字符串
//    NSMutableArray *dataarray = [self getDataArrayWithStartData:starttime endStart:endtime];
//    [BRStringPickerView showStringPickerWithTitle:@"选择时间" dataSource:dataarray defaultSelValue:dataarray[0] isAutoSelect:YES resultBlock:^(id selectValue) {
//
//        timeView.footerLabel.text= selectValue;
//        enddata = selectValue;
//        [self getbaozhengjin];
//
//    }];
//}

-(NSString *)getNowTimeTimestamp2:(NSString *)data{
    
    NSDate* dat;
    if (data == nil) {
        dat = [NSDate dateWithTimeIntervalSinceNow:0];
    }else{
        NSDateFormatter *format = [[NSDateFormatter alloc] init];
        format.dateFormat = @"YYYY-MM-dd";
        dat = [format dateFromString:data];
        }
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    return timeString ;
    
}

- (NSString *)getdataWithTime:(NSString *)time{
    NSTimeInterval newtime=[time doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:newtime];
    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}

- (NSInteger)getdayWithTime:(NSString *)time{
    NSTimeInterval newtime=[time doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:newtime];
    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"dd"];

    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];

    return [currentDateStr integerValue];
}
- (NSInteger)getMothWithTime:(NSString *)time{
    NSTimeInterval newtime=[time doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:newtime];
       NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"MM"];

    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];

    return [currentDateStr integerValue];
}

- (NSInteger)gethourWithTime:(NSString *)time{
    NSTimeInterval newtime=[time doubleValue];
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:newtime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"hh"];
    
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    
    return [currentDateStr integerValue];
}

- (NSInteger)getYearWithTime:(NSString *)time{
    NSTimeInterval newtime=[time doubleValue]+28800;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:newtime];
    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"YYYY"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return [currentDateStr integerValue];
}




- (NSMutableArray *)getDataArrayWithStartData:(NSInteger)start endStart:(NSInteger)end{
    
    NSInteger chaData = end-start;
    NSInteger arrayNum = chaData/86400;
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i<=arrayNum; i++) {
        [array addObject:[self getdataWithTime:[NSString stringWithFormat:@"%ld",start+(i*86400)]]];
    }
    return array;
}

- (void)xuanzeRiqi:(UITapGestureRecognizer *)tap{
    
    MyInfoView *view = (MyInfoView *)[tap view];
// 自定义单列字符串
    [BRStringPickerView showStringPickerWithTitle:@"选择类型" dataSource:[self getRiqi] defaultSelValue:@"线上还款" isAutoSelect:YES resultBlock:^(id selectValue) {
    view.footerLabel.text = selectValue;
        if ([selectValue isEqualToString: @"线上还款"]) {
            type = @"1";
        }
        if ([selectValue isEqualToString: @"线下还款"]) {
            type = @"";
            [df showAlertWithTitle:@"暂未开放" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
            view.footerLabel.text =@"";
            
        }
        if ([selectValue isEqualToString: @"平台贷款"]) {
            type = @"";
            [df showAlertWithTitle:@"暂未开放" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
            view.footerLabel.text =@"";
        }

    
    }];
}
- (NSMutableArray *)getRiqi{
    NSMutableArray *data = [NSMutableArray array];
   [data addObject: @"线上还款"];
    [data addObject:@"线下还款"];
    [data addObject:@"平台贷款"];
    return data;
}

-(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString*)groupId{
    
    if (index == 1) {
        
        status = @"1";
    }
    if (index == 0) {
       
        status = @"2";
        baozhengTextfield.hidden = NO;
        lineView.hidden = NO;
    }
}

- (void)therequest{
    
    
    LoadData *request = [[LoadData alloc]init];
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"CreditCard/detail") withDict:@{@"token":KTokenString,@"card_id":self.card_id} superView:nil isAddtag:NO Block:^(id result) {
        
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            
            NSDictionary *dict = KResultOfKey(@"data");
            infomodel = [MyBankCardModel whc_ModelWithJson:dict];
            
        }
    }];
    
}


#pragma mark layouttabelview

- (void)layouttabelview{
    
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KCONTROLLERWith, KCONTROLLERHeight)];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.tableHeaderView = [self layoutView];
    [self.view addSubview:_tableview];
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableview.backgroundColor = [UIColor whiteColor];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return titlearray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *cellid = [NSString stringWithFormat:@"iii%ld",(long)indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellid];
        [df lineViewWithHeightofTop:50 superView:cell.contentView spacing:-100 color:RGBACOLOR(241, 241, 241, 1) lineHeight:1];
    }
    if (indexPath == nil || indexPath.row>=titlearray.count) {
        return cell;
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    MyBankCardModel *model = titlearray[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@",model.date];
    [cell.textLabel setFont:[UIFont systemFontOfSize:16]];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"快速还款 ¥%.2f",[model.total_price floatValue]];
    [cell.detailTextLabel setFont:[UIFont systemFontOfSize:16]];
    client_num = model.client_num;

    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *backvie = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KCONTROLLERWith, 50)];
    backvie.backgroundColor = [UIColor whiteColor];
    backvie.userInteractionEnabled = YES;
    UILabel *label = [UILabel initWithFrame:CGRectMake(20, 0, KCONTROLLERWith/2-20, 50) text:@"本期未提交计划列表" font:18 textAlignment:NSTextAlignmentLeft texcolor:RGBACOLOR(89, 89, 89, 1) backgroundColor:nil];
    [backvie addSubview:label];
    
    UILabel *touchlabel = [UILabel initWithFrame:CGRectMake(KCONTROLLERWith/2, 0, KCONTROLLERWith/2-20, 50) text:@"清除" font:18 textAlignment:NSTextAlignmentRight texcolor:RGBACOLOR(227, 72, 40, 1) backgroundColor:nil];
    touchlabel.userInteractionEnabled = YES;
    [backvie addSubview:touchlabel];
    [df addTapGestureRecognizerWithTarget:self action:@selector(removeDataScoure) andaddView:touchlabel];
    return backvie;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return (titlearray == nil || titlearray.count == 0)?0:50;
}

- (void)removeDataScoure{
    [titlearray removeAllObjects];
    [_tableview reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}


#pragma mark 提交计划

- (void)tijiao{
    
    [self getbaozhengjin];
    [[HuanKuanAlertview shareSingle] showWithcontent:[NSString stringWithFormat:@"请确保您的信用卡中有¥%@元，否则导致失败还款",margin]];
    [HuanKuanAlertview shareSingle].delegate = self;

}
#pragma mark 提交
- (void)sureButton{
    MyBankCardModel *mode;
    if (titlearray.count != 0 && titlearray != nil) {
        mode = titlearray[0];
    }else{
        return;
    }
    
    LoadData *request = [[LoadData alloc]init];
    [request loadDataPostAsynchronousWithURL:KURLPOSTHeadr(@"CreditPlan/confirm") withDict:@{@"token":KTokenString,@"card_id":self.card_id,@"client_num":mode.client_num} superView:nil isAddtag:YES Block:^(id result) {
        
        NSString *isreturn = [NSString stringWithFormat:@"%@",[result objectForKey:@"status"]];
        if ([isreturn isEqualToString:@"1"]) {
            
            [[HuanKuanAlertview shareSingle] hiddenmyself];
            [self gotBack];
            
        }
    }];
    
}
#pragma mark 计算保证金
- (void)getbaozhengjin{
    
    
    if ([total_price isEqualToString:@""] || total_price ==nil) {
        
//        [df showAlertWithTitle:@"请输入还款金额" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        return ;
    }
    
    if ([startdata isEqualToString:@""] || startdata ==nil) {
        
//        [df showAlertWithTitle:@"请选择开始时间" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        return ;
    }
    
    
    
    if ([total_price floatValue] <1000) {
        
        baozhengjin = [NSString stringWithFormat:@"%.2f",[total_price floatValue]*1.01];
        if ([baozhengjin floatValue] <300) {
            baozhengjinlabel.text = @"保证金额应大于300元";
        }else{
            baozhengjinlabel.text = [NSString stringWithFormat:@"保证金额应大于：%.f元",ceil([baozhengjin floatValue])];
        }
       
        return;
    }
    NSString *startTime = [self getNowTimeTimestamp2:startdata];
    NSString *endtTime = [self getNowTimeTimestamp2:enddata];
    
    NSInteger daynum = ([endtTime floatValue]-[startTime floatValue])/86400+1;
    daynum = daynum>5?5:daynum;
    CGFloat feilvMoney = [total_price floatValue]/(daynum)/2;
    
    float bao = feilvMoney+ [total_price floatValue]*0.01+100;
    baozhengjin = [NSString stringWithFormat:@"%.2f",bao];
    
    if ([baozhengjin floatValue] <500) {
        baozhengjinlabel.text = @"保证金额应大于500元";
    }else{
        baozhengjinlabel.text = [NSString stringWithFormat:@"保证金额应大于：%.f元",ceil([baozhengjin floatValue])];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
